package jwcb.javapjframework.ms_template.service.service;

import com.fasterxml.jackson.core.type.TypeReference;
import jwcb.javapjframework.common.redis.RedisService.service.RedisService;
import jwcb.javapjframework.ms_template.service.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

// TestService.java
@Service
public class TestRedisService {
    
    @Autowired
    private RedisService redisService;

    public String testBasicOperations() {
        // 准备测试数据
        User user = new User(1L, "测试用户");
        String key = "user:" + user.getId();
        
        // 测试基础存储
        redisService.setCacheObject(key, user);
        
        // 测试带过期时间存储
        redisService.setCacheObject(key + ":temp", user, 30L, TimeUnit.SECONDS);
        
        // 测试IfAbsent
        boolean result = redisService.setCacheObjectIfAbsent(key + ":lock", "LOCKED", 10L, TimeUnit.SECONDS);
        
        // 测试获取简单对象
        User cachedUser = redisService.getCacheObject(key, User.class);
        
        // 测试获取复杂泛型对象
        List<User> userList = Arrays.asList(user, new User(2L, "另一个用户"));
        String listKey = "user:list";
        redisService.setCacheObject(listKey, userList);
        
        TypeReference<List<User>> typeRef = new TypeReference<List<User>>() {};
        List<User> cachedList = redisService.getCacheObject(listKey, typeRef);
        
        // 返回测试结果
        return String.format("基础测试完成! IfAbsent结果: %s, 用户: %s, 列表大小: %d",
                             result, cachedUser, cachedList.size());
    }
    
    public String testExpiration() throws InterruptedException {
        String key = "temp:key";
        String value = "临时值";
        
        // 设置短期过期
        redisService.setCacheObject(key, value, 2L, TimeUnit.SECONDS);
        
        // 立即获取应存在
        Object exists = redisService.getCacheObject(key, String.class);
        
        // 等待过期
        Thread.sleep(2500);
        
        // 再次获取应不存在
        Object notExists = redisService.getCacheObject(key, String.class);
        
        return String.format("过期测试: 立即获取=%s, 2.5秒后获取=%s", exists, notExists);
    }

}